<template>
  <div>
    <!-- 查询条件表单 -->
    <el-form :inline="true">
      <el-form-item label="BOM名称">
        <el-input
          v-model="queryConditions.name"
          style="width: 200px"
          size="large"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData(1)">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表组件，监听分页、操作和编辑事件 -->
    <TestPage
      :table-data="tableData"
      :columns="tableColumns"
      :current-page="pageNo"
      :total="allPage"
      :page-size="pageSize"
      @page-change="handlePageChange"
      @action="handleTableAction"
      @edit="openEditDialog"
      @delete="handleDelete"
    />

    <!-- 编辑对话框 -->
    <!-- <bom-edit-dialog
      v-model:visible="editVisible"
      :row="editRow"
      @saved="onSaved"
    /> -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import TestPage from '@/test/TestPage.vue'
import BomEditDialog from '@/basic-view/bom/EditBOM.vue'
import type { BOM } from '@/types/basic/BOM'
import { useRoute,useRouter } from 'vue-router';
import router from '@/router'
import request from '@/util/request'
// 分页与查询状态
const pageNo = ref(1)
const pageSize = ref(3)
const allPage = ref(0)
const queryConditions = reactive({ name: '' })

// 列配置
const tableColumns = ref([
  { prop: 'id',         label: 'BOM ID' },
  { prop: 'name',       label: 'BOM 名称' },
  { prop: 'createDate', label: '创建时间' },
  { prop: 'createUser', label: '创建人' },
  { prop: 'updateDate', label: '更新时间' },
  { prop: 'updateUser', label: '更新人' }
])

// 表格数据
const tableData = ref<BOM[]>([])

// 查询方法
async function fetchData(page: number) {
  try {
    const params = new URLSearchParams()
    params.append('pageNow', page.toString())
    params.append('pageSize', pageSize.value.toString())
    params.append('name', queryConditions.name)
    const resp = await request.post('basic/BOM/getBOMPage', params, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
    const d = resp.data.data
    tableData.value = d.list || []
    allPage.value = d.total || 0
  } catch (error) {
    ElMessage.error('获取BOM数据失败')
    tableData.value = []
    allPage.value = 0
    console.error('获取数据失败：', error)
  }
}

// 分页变化
function handlePageChange(newPage: number) {
  pageNo.value = newPage
  fetchData(newPage)
}

// 操作按钮
function handleTableAction(actionName: string) {
  switch(actionName){
        case 'add':
          router.push('/home/basic/AddBOM')
          break 
      }
  console.log('触发操作：', actionName)
}

// 重置条件
function reset() {
  queryConditions.name = ''
  fetchData(1)
}

const editVisible = ref(false)
const editRow = ref<BOM | null>(null)


function openEditDialog(row: BOM) {
  console.log('编辑按钮点击：', row.id)
  router.push({
            name:'EditBOM',
            params:{
              id:row.id
            }
          })
}

function onSaved() {
  editVisible.value = false
  fetchData(pageNo.value)
}
async function handleDelete(row: BOM) {
  try {
    await ElMessageBox.confirm(
      '确定要删除该BOM吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const id = row.id
    console.log('删除id:', row.id)
    const response = await request.post('basic/BOM/delBOM', { id }, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })

    if (response.data.code == 200) {
      ElMessage.success('删除成功')
      router.push('BOMLimitPage')
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
    fetchData(1)
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('删除操作失败或发生错误')
    } else {
      ElMessage.info('已取消删除')
    }
  }
}
fetchData(1)
</script>

<style scoped>
</style>
